import axios from 'axios'
// 导入store对象,拿到token
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 统一携带token
    const token = store.getters.token
    if (token) {
      // 配置请求头
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => { // 2xx
    const { message, success } = response.data
    // 登录失败,中断程序执行
    if (!success) return Promise.reject(new Error(message))
    // 登录成功,返回服务器响应的数据
    return response.data
  },
  error => {
    // console.dir(error)
    const { code } = error.response.data
    if (code === 10002) {
      // 重置用户信息
      store.commit('user/RESET_STATE')
      // 删除本地cookie里的数据
      store.commit('user/REMOVE_TOKEN')
      // 强制跳转到登录页 携带未遂地址 进行编码传参
      // console.log(router)
      router.replace(`/login?redirect=${encodeURIComponent(router.currentRoute.fullPath)}`)
    }
    return Promise.reject(error)
  }
)

export default service
